use crate::error::{with_context, SysError};
use std::path::Path;
use std::process::{Command, Stdio};

pub fn run_command(current_dir: &Path, command_name: &str, args: &[&str]) -> Result<(), SysError> {
    let mut cmd = Command::new(command_name);
    cmd.current_dir(current_dir);

    for arg in args {
        cmd.arg(arg);
    }

    let mut output = cmd
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn()
        .map_err(|err| with_context(err, &format!("{}执行出错", command_name)))?;

    let status = output
        .wait()
        .map_err(|err| with_context(err, &format!("等待命令错误:{}", command_name)))?;

    // 检查命令是否成功执行
    if !status.success() {
        eprintln!("Error running npm: {:?}", output.stderr);
        return Err(SysError::msg(&format!("Failed to run {}", command_name)));
    }
    Ok(())
}
